<?php
/**
 * Created By Project
 * Author: 陈东
 * Copyright：陈东
 * Source Code：陈东
 * Explain：I shall not authorize for any other commercial purposes, law breakers must be prosecuted.
 */
namespace Home\Controller;
use Think\Controller;

class FmdataController extends BaseController {
	
	private $appsecret = '1949b762437558d0c7da8b44257525bc';
	private $appkey = '4cf3f278c4d1a62f36e528b0099b9461';
	//private $pack_id = 'com.ushaqi.zhuishushenqi';
	private $pack_id = 'com.ushaqi.zhuishushenqi';

    public function index(){
    	echo "access_token:".$this->get_access_token();die;
    }
    
    /*
     * 返回分类列表
     */
    public function infolist(){
    	//echo $this->get_access_token();die;
    	$url = "http://api.ximalaya.com/categories/list";
    	$fieldarray = array(
    			'app_key'			=>	$this->appkey,
    			'client_os_type'	=>	3,
    			'device_id'			=>	$this->get_device_id(),
    			'pack_id'			=>	$this->pack_id,
    			'access_token'		=>	$this->get_access_token(),
    	);
    	$get_value = $this->get_info_content($url, $fieldarray);
    	//dump($get_value);die;
    	
    	$this->assign('category',$this->arr($get_value));
    	$this->display();
    }
    
    /*
     * 返回标签列表
     */
    public function category_info(){
    	$category_id = I('get.category_id',0);
    	$url = "http://api.ximalaya.com/v2/tags/list";
    	$fieldarray = array(
    			'app_key'			=>	$this->appkey,
    			'client_os_type'	=>	3,
    			'device_id'			=>	$this->get_device_id(),
    			'pack_id'			=>	$this->pack_id,
    			'access_token'		=>	$this->get_access_token(),
    			'category_id'		=>	$category_id,
    			'type'				=>	0  //0-专辑标签，1-声音标签
    	);
    	$get_value = $this->get_info_content($url, $fieldarray);
    	//dump($get_value);die;
    	
    	$this->assign('categoryinfo',$this->arr($get_value));
    	$this->assign('category_id',$category_id);
    	$this->display();
    }
    
    /*
     * 返回分类与标签下的内容
     */
    public function albums_list(){
		$tag_name = iconv("gb2312","utf-8",$_GET['tag_name']);
    	$category_id = I('get.category_id',0);

    	$url = "http://api.ximalaya.com/v2/albums/list";
    	$fieldarray = array(
    			'app_key'			=>	$this->appkey,
    			'client_os_type'	=>	3,
    			'device_id'			=>	$this->get_device_id(),
    			'pack_id'			=>	$this->pack_id,
    			'access_token'		=>	$this->get_access_token(),
    			'category_id'		=>	$category_id,
    			'tag_name'			=>	$tag_name,
    			'page'				=>	1,
    			'count'				=>	20,
    			'calc_dimension'	=>	3 //现支持最火（1），最新（2），经典或播放最多（3）
    	);
    	//dump($fieldarray);die;
    	$get_value = $this->get_info_content($url, $fieldarray);

    	//dump($get_value);die;
		$this->assign('albumslist',$get_value['albums']);
		$this->display();

    }

    
    public function browselist(){
		$album_id = I('get.album_id',0);
		$url = "http://api.ximalaya.com/albums/browse";
		$fieldarray = array(
				'app_key'			=>	$this->appkey,
				'client_os_type'	=>	3,
				'device_id'			=>	$this->get_device_id(),
				'pack_id'			=>	$this->pack_id,
				'access_token'		=>	$this->get_access_token(),
				'album_id'			=>	$album_id,
				//'page'				=>	1,
				//'count'				=>	20,
		);
    	$get_value = $this->get_info_content($url, $fieldarray);
		//print_r($get_value);die;
    	$this->assign('browselist',$get_value['tracks']);
    	$this->display();
    }

    
    /*
     * 公用 返回信息内容
     */
    protected function get_info_content($url,$fieldarray){
    	$fieldarray = $this->get_this_sig($fieldarray);
    	$str = null;
    	foreach ($fieldarray as $key=>$v){
    		$str .= $key.'='.$v.'&';
    	}
    	$url = $url."?".rtrim($str,'&');
    	$res = $this->request_post($url, $fieldarray, 0);
    	return json_decode($res,true);
    }
    
    /*
     * 获取access_token
     */
    protected function get_access_token($fieldarray = null){
    	$appsecret 		=	$this->appsecret;
    	$appkey 		=	$this->appkey;
    	$device_id 		=	$this->get_device_id();
    	$grant_type 	=	'client_credentials';
    	$nonce 			=	$this->get_random_str();
    	$timestamp 		=	$this->unixtime();
    	$fieldarray = array(
    			'device_id'		=>	$device_id,
    			'nonce'			=>	$nonce,
    			'timestamp'		=>	$timestamp,
    			'client_id'		=>	$appkey,
    			'grant_type'	=>	$grant_type
    	);
    	
    	$url = "http://api.ximalaya.com/oauth2/secure_access_token";
    	$res = $this->request_post($url, $this->get_this_sig($fieldarray));
    	//print_r($res);die;
    	$jsonresult = json_decode($res);
    	$access_token = $jsonresult->access_token;
    	return $access_token;
    }
    
    /*
     * 获取当前API接口的sig并拼接
     */
    protected function get_this_sig($field_array){
    	$str = null;
    	$fieldarray = $field_array;
    	ksort($fieldarray);
    	foreach ($fieldarray as $key=>$v){
    		$str .= $key.'='.$v.'&';
    	}
    	$str = rtrim($str,'&');
    	$str_base64 = base64_encode($str);
    	$sig = md5(hash_hmac("sha1", $str_base64, $this->appsecret, true));
    	$fieldarray['sig'] = $sig;
    	return $fieldarray;
    }
    
    /*
     * 获取cookie('device_id')值
     */
    protected function get_device_id(){
    	if(!empty(cookie('device_id'))){
    		$get_device_id = cookie('device_id');
    	}else{
    		$get_device_id = $this->get_random_str(20);
    		cookie('device_id',$get_device_id);
    	}
    	return $get_device_id;
    }
    
    /*
     * 获取access_token
     * $url API地址
     * $post_data 参数数组
     */
    protected function request_post($url = '', $post_data = array(), $method = 1) {
    	if (empty($url) || empty($post_data)){
    		return false;
    	}
    	$o = "";
    	foreach($post_data as $k => $v ){
    		$o.= "$k=" . urlencode( $v ). "&" ;
    	}
    	$post_data = substr($o,0,-1);  
    	$postUrl = $url;
    	$curlPost = $post_data;
    	$ch = curl_init();//初始化curl
    	if($method==1){
    		curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    	}else{
    		curl_setopt($ch, CURLOPT_URL,$url);
    	}    	
    	curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    	if($method==1){
    		curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    		curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    	}
    	$data = curl_exec($ch);//运行curl
    	curl_close($ch);
    	return $data;
    }
    
    /*
     * 毫秒数时间戳
     */
    protected function unixtime(){
    	$time = explode(" ", microtime ());
    	$time = $time[1].($time [0] * 1000);
    	$time2 = explode(".", $time);
    	$time = $time2[0];
    	return $time;
    }

    /*
     * 生成随机数字
     */
    protected function get_random_str( $length = 15 ) {
    	// 密码字符集，可任意添加你需要的字符
    	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    	$password = '';
    	for ( $i = 0; $i < $length; $i++ ){
    		// 这里提供两种字符获取方式
    		// 第一种是使用 substr 截取$chars中的任意一位字符；
    		// 第二种是取字符数组 $chars 的任意元素
    		// $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    		$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    	}
    	return $password;
    }
    
    /*
     * 对象转数组（object to array）
     */
    protected function object_to_array($obj){
    	$_arr = is_object($obj)? get_object_vars($obj) : $obj;
    	foreach ($_arr as $key => $val) {
    		$val = (is_array($val)) || is_object($val) ? object_to_array($val) : $val;
    		$arr[$key] = $val;
    	}
    	return $arr;
    }
    
    protected function object_array($array) {
    	if(is_object($array)) {
    		$array = (array)$array;
    	} if(is_array($array)) {
    		foreach($array as $key=>$value) {
    			$array[$key] = object_array($value);
    		}
    	}
    	return $array;
    }
    
    /*
     * object to array 再组合
     */
    protected function arr($result){
    	$dataarray = array();
    	foreach($result as $val){
			$dataarray[] = $this->object_to_array($val);
    	}
    	return $dataarray;
    }
}